package com.kt.NetworkModel.net

import android.view.Gravity
import com.blankj.utilcode.util.ActivityUtils
import com.kt.NetworkModel.App
import com.kt.NetworkModel.utils.LoadingNetUtils
import com.kt.NetworkModel.utils.MLog
import com.kt.NetworkModel.utils.ToastUtils
import com.kt.network.bean.BaseResult
import com.tencent.mmkv.MMKV
import io.reactivex.Observer
import io.reactivex.disposables.Disposable


abstract class CallBack<T> : Observer<BaseResult<T>> {
    override fun onSubscribe(d: Disposable) {
    }

    override fun onNext(t: BaseResult<T>) {
        if (t.isSuccess()) {
            onResult(t.data)
        } else {
            LoadingNetUtils.getInstance().dismissLoading()
            if (!onError(t.desc, t.code)) {
                if (t.code == 10086) {
                    MMKV.defaultMMKV().putBoolean("isLogin", false)
//                    val intent = Intent()
//                    intent.setClassName(App.get(), "com.ghn.cocknovel.ui.activity.start.StartActivity")
//                    App.get().startActivity(intent)
                    ActivityUtils.startActivity("com.ghn.cocknovel", "com.ghn.cocknovel.ui.activity.start.StartActivity")
                } else {
                    val toastUtils = ToastUtils(App.get())
                    toastUtils.InitToast()
                    toastUtils.setGravity(Gravity.CENTER)
                    toastUtils.setText(t.desc)
                    toastUtils.show()
                }
            }
        }
    }

    override fun onError(e: Throwable) {
//        Toaster.show("网络访问失败！" + e.message)
        MLog.d(e.message.toString())
        onError(e.message.toString(), -100)
    }

    open fun onError(e: String, code: Int): Boolean {
        return false
    }

    override fun onComplete() {
    }

    abstract fun onResult(result: T?)

}